package xlj.lib.android.base.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import xlj.lib.android.base.toastcompat.ToastManager;

import static android.app.Activity.RESULT_OK;

/**
 * Created by qyx on 2017/3/14.
 */

public class PictureSelectUtils {
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static File file;

    private static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static void goToCamera(Activity activity) {
        if (hasSdcard()) {
            File f = new File(Environment.getExternalStorageDirectory() + "/redgress");
            if (!f.exists())
                f.mkdirs();
            file = new File(f, System.currentTimeMillis() + ".jpg");
            Uri imageUri;
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                openCameraIntent.addFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION);
                imageUri = FileProvider.getUriForFile(activity, getFileProviderName(activity), file);

            } else {
                imageUri = Uri.fromFile(file);
            }


            //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
//            openCameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            activity.startActivityForResult(openCameraIntent, PHOTO_REQUEST_CAREMA);
        }
    }

    public static void goToPicture(Activity activity) {
        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK);
        openAlbumIntent.setType("image/*");
        activity.startActivityForResult(openAlbumIntent, PHOTO_REQUEST_GALLERY);
    }


    public static String getPictureUrl(Activity context, int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == PHOTO_REQUEST_GALLERY) {
                // 从相册返回的数据
                if (data != null) {
                    try {
                        String path = getFilePathWithDocumentsUri(data.getData(), context);
                        return path;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else if (requestCode == PHOTO_REQUEST_CAREMA) {
                // 从相机返回的数据
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    if (file.canRead()) {
                        return file.getPath();
                    }
                } else {
                    ToastManager.getInstance().showToast("未找到存储卡，无法存储照片！");
                }
            }
        }
        return "";
    }

    /**
     * 通过从文件中得到的URI获取文件的路径
     *
     * @param uri
     * @param activity
     * @return Author JPH
     * Date 2016/6/6 0006 20:01
     */
    public static String getFilePathWithDocumentsUri(Uri uri, Activity activity) throws Exception {
        if (uri == null) {
            return null;
        }

        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && uri.getPath().contains("document")) {
            File tempFile = getTempFile(activity, uri);
            try {
                inputStreamToFile(activity.getContentResolver().openInputStream(uri), tempFile);

                return tempFile.getPath();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new Exception("");
            }
        } else {
            return getFilePathWithUri(uri, activity);
        }
    }

    /**
     * 通过URI获取文件的路径
     *
     * @param uri
     * @param activity
     * @return Author JPH
     * Date 2016/6/6 0006 20:01
     */
    public static String getFilePathWithUri(Uri uri, Activity activity) throws Exception {
        if (uri == null) {
            throw new Exception("");
        }
        File picture = getFileWithUri(uri, activity);
        String picturePath = picture == null ? null : picture.getPath();
        if (TextUtils.isEmpty(picturePath))
            throw new Exception("");
        if (!checkMimeType(activity, getMimeType(activity, uri)))
            throw new Exception("");
        return picturePath;
    }

    /**
     * 检查文件类型是否是图片
     *
     * @param minType
     * @return
     */
    public static boolean checkMimeType(Context context, String minType) {
//        boolean isPicture = !TextUtils.isEmpty(minType) && (".jpg|.gif|.png|.bmp|.jpeg|.webp|".contains(minType.toLowerCase()));
        boolean isPicture = !TextUtils.isEmpty(minType) && (".jpg|.gif|.png|.jpeg|".contains(minType.toLowerCase()));
        if (!isPicture)
            ToastManager.getInstance().showToast("请选择jpg、png、gif、jpeg格式的图片");
        return isPicture;
    }

    /**
     * To find out the extension of required object in given uri
     * Solution by http://stackoverflow.com/a/36514823/1171484
     */
    public static String getMimeType(Activity context, Uri uri) {
        String extension;
        //Check uri format to avoid null
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            //If scheme is a content
            extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getContentResolver().getType(uri));
            if (TextUtils.isEmpty(extension))
                extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
        } else {
            //If scheme is a File
            //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
            extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
            if (TextUtils.isEmpty(extension))
                extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getContentResolver().getType(uri));
        }
        if (TextUtils.isEmpty(extension)) {
            extension = getMimeTypeByFileName(getFileWithUri(uri, context).getName());
        }
        return extension;
    }


    public static String getMimeTypeByFileName(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."), fileName.length());
    }


    /**
     * 通过URI获取文件
     *
     * @param uri
     * @param activity
     * @return Author JPH
     * Date 2016/10/25
     */
    public static File getFileWithUri(Uri uri, Activity activity) {
        String picturePath = null;
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.getContentResolver().query(uri,
                    filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            if (columnIndex >= 0) {
                picturePath = cursor.getString(columnIndex);  //获取照片路径
            } else if (TextUtils.equals(uri.getAuthority(), getFileProviderName(activity))) {
                picturePath = parseOwnUri(activity, uri);
            }
            cursor.close();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            picturePath = uri.getPath();
        }
        return TextUtils.isEmpty(picturePath) ? null : new File(picturePath);
    }

    public final static String getFileProviderName(Context context) {

        return context.getApplicationContext().getPackageName() + ".fileProvider";
    }


    /**
     * 提供的Uri 解析出文件绝对路径
     *
     * @param uri
     * @return
     */
    public static String parseOwnUri(Context context, Uri uri) {
        if (uri == null) return null;
        String path;
        if (TextUtils.equals(uri.getAuthority(), getFileProviderName(context))) {
            path = new File(uri.getPath().replace("camera_photos/", "")).getAbsolutePath();
        } else {
            path = uri.getPath();
        }
        return path;
    }

    /**
     * InputStream 转File
     */
    public static void inputStreamToFile(InputStream is, File file) throws Exception {
        if (file == null) {
            throw new Exception("");
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024 * 10];
            int i;
            while ((i = is.read(buffer)) != -1) {
                fos.write(buffer, 0, i);
            }
        } catch (IOException e) {
            throw new Exception("");
        } finally {
            try {
                fos.flush();
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取临时文件
     *
     * @param context
     * @param photoUri
     * @return
     */
    public static File getTempFile(Activity context, Uri photoUri) throws Exception {
        String minType = getMimeType(context, photoUri);
        if (!checkMimeType(context, minType)) throw new Exception("");
        File filesDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!filesDir.exists()) filesDir.mkdirs();
        File photoFile = new File(filesDir, UUID.randomUUID().toString() + "." + minType);
        return photoFile;
    }

    public static File getCropTempPhoto() {
        File file = new File(Environment.getExternalStorageDirectory(),"redgrass/crop");
        if (!file.exists())file.mkdirs();
        File photoFile = new File(file, UUID.randomUUID().toString() + ".jpg" );
        return photoFile;
    }
}
